package de.gzork.server;

import java.util.Enumeration;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.w3c.dom.Document;

import com.google.code.facebookapi.ErrorCode;
import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookXmlRestClient;
import com.google.code.facebookapi.IFacebookRestClient;

public class FacebookHelper {

	private String api_key = "4153a065027a515064a75ccbd317e7f1";
	private String secret = "1ec80a3ec5b3b40cb014b9db186130d1";

	HttpServletRequest _request;
	HttpServletResponse _response;

	public static final String FACEBOOK_USER_ID = "facebook.user.id";

	private HttpSession _session;
	private IFacebookRestClient<Document> _userClient;

	@SuppressWarnings("unused")
	private FacebookHelper() {

	}

	public FacebookHelper(HttpServletRequest request, HttpServletResponse response) {
		_request = request;
		_response = response;
		_session = _request.getSession(true);
	}

	public boolean login(String authToken) throws Exception {

		boolean ret = false;

		if (authToken != null && authToken.length() > 0) {
			System.out.println("Login mit Auth-Token: " + authToken);
			_userClient = new FacebookXmlRestClient(api_key, secret);
			String sessionKey = _userClient.auth_getSession(authToken);
			_userClient = new FacebookXmlRestClient(api_key, secret, sessionKey);
			_session.setAttribute(FACEBOOK_USER_ID, getUserID());
			_session.setAttribute("session_key", sessionKey);
			ret = true;
		} else {
			throw new Exception("redirect!");
		}
		if (getUserID() < 0) {
			throw new Exception("Fehler beim Login!");
		}
		return ret;
	}

	public long getUserID() {
		long facebookUserID = -1;
		try {
			facebookUserID = _userClient.users_getLoggedInUser();
			System.out.println("facebookUserID = " + facebookUserID);
		} catch (FacebookException ex) {
			if (ex.getCode() == ErrorCode.SESSION_INVALID) {
				System.out.println("Session Invalid!");
				clearSession();
			}
			System.out.println("ERROR-CODE: " + ex.getCode());
			System.out.println(ex.getMessage());
		}

		return facebookUserID;
	}

	private void clearSession() {
		_userClient = null;
		_session.removeAttribute("FACEBOOK_USER_ID");
		_session.removeAttribute("session_key");
	}

}
